<?php

class Rsalib
{

   	 	/**
     		* 钥匙长度
     		*/
				private $_bits;
       
        /**
         * 公钥
         */
        private $_pubKey;
       
        /**
         * 钥匙目录
         */
        private $_keyPath;
       
        /**
         * 加载钥匙目录
         */
        public function __construct($bit = 1024)
				{
					$this->_keyPath = APPPATH.'channels/include/feiliu/data/rsakey';  //以实际地址为准
					$this->_bits = $bit;
        }
       
        public function __destruct()
        {
          @ fclose($this->_pubKey);
        }
       
        /**
         * 设置公钥
         */
        public function setupPubKeyByCompanyId($companyId)
        {
          if(is_resource($this->_pubKey))
          {
              return true;
          }
          $file = $this->_keyPath . DIRECTORY_SEPARATOR . $companyId . '_SignKey.pub';  
          $puk = file_get_contents($file);
          $this->_pubKey = openssl_pkey_get_public($puk);
          return true;
        }
         /**
         * 公钥解密 
         */
        public function pubDecryptByCompanyId($crypted, $gameId)
        {
					if(!is_string($crypted))
					{
          	return null;
          }
               
          $this->setupPubKeyByCompanyId($gameId);
               
         	$crypted = base64_decode($crypted);

          $r = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey);

					if($r)
					{
          	return $decrypted;
          }
          return null;
				}

}

?>
